import React, { useEffect, useState } from 'react';
import { Card, Avatar, List, Button, Space, Statistic, Row, Col, message, Spin, Typography, Modal, Upload, Tag } from 'antd';
import {
    UserOutlined,
    HeartOutlined,
    StarOutlined,
    SettingOutlined,
    TeamOutlined,
    ShoppingOutlined,
    MedicineBoxOutlined,
    GiftOutlined,
    ManOutlined,
    WomanOutlined,
    UploadOutlined,
    PlusOutlined
} from '@ant-design/icons';
import styled from 'styled-components';
import { useNavigate } from 'react-router-dom';
import api, { API_BASE_URL } from '../services/api';
import { User } from '../store/slices/userSlice';
import type { UploadProps } from 'antd';
import { RcFile, UploadChangeParam, UploadFile } from 'antd/es/upload/interface';

const { Title } = Typography;

const StyledCard = styled(Card)`
  margin-bottom: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  position: relative;
`;

const EditButton = styled(Button)`
  position: absolute;
  top: 16px;
  right: 16px;
  z-index: 1;
`;

const StatsCard = styled(StyledCard)`
  .ant-statistic {
    text-align: center;
  }
  .ant-statistic-title {
    font-size: 14px;
    color: #666;
  }
  .ant-statistic-content {
    font-size: 20px;
    color: #1890ff;
  }
  .ant-statistic-content-prefix {
    margin-right: 8px;
  }
`;

const ProfileHeader = styled.div`
  text-align: center;
  padding: 24px 0;
`;

const UserName = styled.h2`
  margin: 16px 0 8px;
  display: flex;
  align-items: center;
  justify-content: center;
`;

const UserInfo = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-bottom: 8px;
`;

const UserInfoItem = styled.span`
  color: #666;
  font-size: 0.9em;
`;

const EmailText = styled.p`
  color: #666;
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 0.9em;
`;

const UserBio = styled.p`
  color: #666;
  margin-bottom: 16px;
`;

const StyledModal = styled(Modal)`
  .ant-modal-content {
    border-radius: 8px;
  }
  .ant-modal-body {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 24px;
  }
  .ant-upload.ant-upload-select {
    margin: 0 auto;
  }
  .ant-modal-footer {
    border-top: none;
    padding: 0 24px 24px;
    text-align: center;
  }
  .ant-modal-footer .ant-btn {
    min-width: 100px;
  }
`;

// 兴趣标签卡片的新样式组件
const TagsCard = styled(StyledCard)`
  .ant-card-head-title {
    padding: 16px 0;
  }
  .ant-tag {
      margin-bottom: 8px;
  }
`;

// 新增的样式组件：添加标签按钮
const AddTagButton = styled(Button)`
  position: absolute;
  top: 16px;
  right: 16px;
  z-index: 1;
`;

// 定义菜单项的类型
interface MenuItem {
    icon: React.ReactNode;
    title: string;
    description: string;
    path?: string; // 导航的可选路径
    onClick?: () => void; // 添加可选的 onClick 处理函数
}

const Profile: React.FC = () => {
    const navigate = useNavigate();
    const [userData, setUserData] = useState<User | null>(null);
    const [loading, setLoading] = useState(true);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [fileList, setFileList] = useState<UploadFile[]>([]);
    const [uploading, setUploading] = useState(false);

    // 获取性别图标的辅助函数
    const getGenderIcon = (gender: string | undefined) => {
        if (!gender) return null;
        if (gender === 'male') return <ManOutlined style={{ color: '#1890ff', marginRight: 8 }} />;
        if (gender === 'female') return <WomanOutlined style={{ color: '#eb2f96', marginRight: 8 }} />;
        return null; // 或者 '其他' 的默认图标
    };

    useEffect(() => {
        const fetchUserProfile = async () => {
            try {
                setLoading(true);
                const token = localStorage.getItem('userToken');
                if (!token) {
                    message.error('未认证，请先登录。');
                    navigate('/login');
                    return;
                }

                const response = await api.auth.getUserProfile(token);

                if (response.success && response.user) {
                    setUserData(response.user);
                } else {
                    message.error(response.message || '获取用户资料失败');
                }
            } catch (error) {
                console.error('Error fetching user profile:', error);
                message.error('获取用户资料失败');
            } finally {
                setLoading(false);
            }
        };

        fetchUserProfile();
    }, [navigate]);

    const handleAvatarClick = () => {
        setIsModalVisible(true);
    };

    const handleModalCancel = () => {
        setIsModalVisible(false);
    };

    const handleFileChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
        setFileList(newFileList.slice(-1)); // 只保留最后一个文件
    };

    const handleUpload = async () => {
        if (fileList.length === 0) {
            message.error('请先选择图片');
            return;
        }

        const file = fileList[0].originFileObj as RcFile;
        const formData = new FormData();
        formData.append('avatar', file);

        setUploading(true);
        try {
            const uploadResponse = await api.upload.uploadAvatar(formData);
            if (uploadResponse.success && uploadResponse.url) {
                const token = localStorage.getItem('userToken');
                if (!token) {
                    message.error('未认证，请先登录。');
                    return;
                }

                const response = await api.auth.updateUserProfile(token, { avatar: uploadResponse.url });
                if (response.success && response.user) {
                    setUserData(response.user);
                    message.success('头像更新成功！');
                    setIsModalVisible(false);
                    setFileList([]);
                } else {
                    message.error(response.message || '更新用户资料失败');
                }
            } else {
                message.error(uploadResponse.message || '头像上传失败');
            }
        } catch (error) {
            console.error('Avatar upload failed:', error);
            message.error('头像上传失败');
        } finally {
            setUploading(false);
        }
    };

    if (loading) {
        return (
            <div style={{ textAlign: 'center', marginTop: '50px' }}>
                <Spin size="large"></Spin>
            </div>
        );
    }

    if (!userData) {
        return (
            <div style={{ textAlign: 'center', marginTop: '50px' }}>
                <Title level={4}>无法加载用户资料</Title>
                <Button type="primary" onClick={() => navigate(-1)}>返回</Button>
            </div>
        );
    }

    // 明确指定 menuItems 的类型
    const menuItems: MenuItem[] = [
        {
            icon: <TeamOutlined />,
            title: '我的圈子',
            description: '查看我加入的兴趣圈子',
            onClick: () => message.info('功能开发中ing，请期待~'), // 添加占位符处理函数
        },
        {
            icon: <ShoppingOutlined />,
            title: '我的订单',
            description: '查看我的消费记录',
            onClick: () => message.info('功能开发中ing，请期待~'), // 添加占位符处理函数
        },
        {
            icon: <MedicineBoxOutlined />,
            title: '健康管理',
            description: '查看健康数据和计划',
            onClick: () => message.info('功能开发中ing，请期待~'), // 添加占位符处理函数
        },
        {
            icon: <GiftOutlined />,
            title: '我的服务',
            description: '宠物服务等',
            onClick: () => message.info('功能开发中ing，请期待~'), // 添加占位符处理函数
        }
    ];

    // 添加设置菜单项，updatedMenuItems 也将是 MenuItem[] 类型
    const updatedMenuItems: MenuItem[] = [
        ...menuItems,
        {
            icon: <SettingOutlined />,
            title: '我的设置',
            description: '应用通用设置',
            path: '/settings', // 保留导航路径
            // onClick 处理函数将由下面的 List.Item onClick 逻辑处理
        }
    ];

    return (
        <div>
            <StyledCard>
                <EditButton
                    type="primary"
                    onClick={() => navigate('/profile/edit')}
                >
                    编辑资料
                </EditButton>
                <ProfileHeader>
                    <Avatar
                        size={80}
                        src={userData.avatar ? `${API_BASE_URL.replace('/api', '')}${userData.avatar}` : undefined}
                        icon={<UserOutlined />}
                        onError={() => {
                            setUserData(prev => prev ? { ...prev, avatar: undefined } : null);
                            return true;
                        }}
                        style={{ cursor: 'pointer' }}
                        onClick={handleAvatarClick}
                    />
                    <UserName>{getGenderIcon(userData.gender)}{userData.username}</UserName>
                    <UserInfo>
                        {(userData.age !== null && userData.age !== undefined && userData.age !== 0) && <UserInfoItem>{userData.age}岁</UserInfoItem>}
                        {userData.zodiacSign && <UserInfoItem>{userData.zodiacSign}</UserInfoItem>}
                    </UserInfo>
                    {userData.email && <EmailText>{userData.email}</EmailText>}
                    <UserBio>{userData.bio || '这个人很懒，什么都没留下'}</UserBio>
                </ProfileHeader>
            </StyledCard>

            <StatsCard>
                <Row gutter={[16, 16]}>
                    <Col span={8}>
                        <Statistic
                            title="关注"
                            value={userData.followingCount || 0}
                            prefix={<HeartOutlined />}
                        />
                    </Col>
                    <Col span={8}>
                        <Statistic
                            title="收藏"
                            value={userData.favoritesCount || 0}
                            prefix={<StarOutlined />}
                        />
                    </Col>
                    <Col span={8}>
                        <Statistic
                            title="积分"
                            value={userData.points || 0}
                            prefix={<GiftOutlined />}
                        />
                    </Col>
                </Row>
            </StatsCard>

            <TagsCard title="兴趣标签">
                <AddTagButton
                    type="dashed"
                    size="small"
                    onClick={() => navigate('/profile/tags')}
                >
                    <PlusOutlined /> 添加/编辑标签
                </AddTagButton>
                {(userData?.interestTags || []).map(tag => (
                    <Tag key={tag.id} color="blue">
                        {tag.name}
                    </Tag>
                ))}
            </TagsCard>

            <StyledCard>
                <List
                    itemLayout="horizontal"
                    dataSource={updatedMenuItems}
                    renderItem={(item: MenuItem) => (
                        <List.Item
                            // 修改 actions：如果 item 有 onClick，则隐藏 action 按钮
                            actions={item.onClick && !item.path ? [] : [<Button type="text" onClick={item.onClick || (() => { })}>管理</Button>]} // 根据 item 属性调整 action 按钮
                            onClick={() => {
                                if (item.path) {
                                    navigate(item.path);
                                } else if (item.onClick) { // 如果没有路径，则使用 item 的 onClick
                                    item.onClick();
                                }
                            }}
                            style={{ cursor: (item.path || item.onClick) ? 'pointer' : 'default' }} // 如果可点击则改变光标样式
                        >
                            <List.Item.Meta
                                avatar={item.icon}
                                title={item.title}
                                description={item.description}
                            />
                        </List.Item>
                    )}
                />
            </StyledCard>

            <StyledModal
                title="更换头像"
                open={isModalVisible}
                onCancel={handleModalCancel}
                footer={[
                    <Button
                        key="upload"
                        type="primary"
                        onClick={handleUpload}
                        loading={uploading}
                        disabled={fileList.length === 0}
                        style={{ marginBottom: 8 }}
                    >
                        更换
                    </Button>,
                    <Button key="cancel" onClick={handleModalCancel}>
                        取消
                    </Button>
                ]}
                centered
            >
                <Upload
                    listType="picture-card"
                    fileList={fileList}
                    onChange={handleFileChange}
                    beforeUpload={() => false}
                    maxCount={1}
                >
                    {fileList.length === 0 && (
                        <div>
                            <UploadOutlined />
                            <div style={{ marginTop: 8 }}>选择图片</div>
                        </div>
                    )}
                </Upload>
            </StyledModal>
        </div>
    );
};

export default Profile; 